package com.chuangyang.fixboxlib.utils;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Point;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.view.Display;
import android.view.WindowManager;
import android.widget.Toast;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

/**
 * Created by vanshu on 15/3/21 14:49.
 */
public class StringUtils {
    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }


    public static String encodeUrl(HashMap<String, String> parameters) {
        if (parameters == null || parameters.size() == 0)
            return "";
        StringBuilder sb = new StringBuilder();
        sb.append("?");
        boolean first = true;
        for (String key : parameters.keySet()) {
            if (first)
                first = false;
            else
                sb.append("&");
            sb.append(key + "=" + parameters.get(key));
        }
        return sb.toString();
    }


    public static Bundle getMetaData(Context context) {
        Bundle bundle = null;
        try {
            bundle = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_ACTIVITIES | PackageManager.GET_META_DATA).metaData;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return bundle;
    }


    public static String getDeviceName() {
        String manufacturer = Build.MANUFACTURER;
        String model = Build.MODEL;
        if (model.startsWith(manufacturer)) {
            return capitalize(model);
        } else {
            return capitalize(manufacturer) + " " + model;
        }
    }


    private static String capitalize(String s) {
        if (s == null || s.length() == 0) {
            return "";
        }
        char first = s.charAt(0);
        if (Character.isUpperCase(first)) {
            return s;
        } else {
            return Character.toUpperCase(first) + s.substring(1);
        }
    }

    public static String getDeviceOsVersion() {
        return Build.VERSION.RELEASE;
    }

    public static String getVersionCode(Context context) {
        int versionCode = 0;
        try {
            versionCode = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return String.valueOf(versionCode);
    }

    public static String getVersionName(Context context) {
        try {
            return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }


    public static String getScreenSizeInPx(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        int width = size.x;
        int height = size.y;
        return width + "*" + height;
    }

    public static int getNumStar(int rate) {
        if (rate > 80 && rate <= 100) {
            return 5;
        } else if (rate > 60 && rate <= 80) {
            return 4;
        } else if (rate > 40 && rate <= 60) {
            return 3;
        } else if (rate > 20 && rate <= 40) {
            return 2;
        } else {
            return 1;
        }
    }

    public static String convertDistance(String str) {
        if (str != null && str.contains(".")) {
            return str.substring(0, str.indexOf("."));
        } else {
            return str;
        }
    }

    public static String displayDistance(String str) {
//        int distance = Integer.parseInt(str);
//        if (distance < 1000) {
//            return distance + "米";
//        } else if (distance > 1000) {
//            return String.valueOf(Double.parseDouble(str) / 1000).substring(0,) + "千米";
//        } else {
//            return "";
//        }
        return null;
    }


    public static void dialPhone(Context context, String phoneNumber) {
        if (phoneNumber == null||phoneNumber.equals("")) {
            Toast.makeText(context, "电话号码为空", Toast.LENGTH_SHORT).show();
            return;
        }
        Uri uri = Uri.parse("tel:" + phoneNumber);
        Intent intent = new Intent(Intent.ACTION_DIAL, uri);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }


    public static String convertDate(String date) {
        String result = "";
        try {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date convertDate = df.parse(date);
            result = new SimpleDateFormat("MM月dd日 HH:mm").format(convertDate);
        } catch (Exception e) {

        }
        return result;
    }

    // 获取ApiKey 百度推送
    public static String getMetaValue(Context context, String metaKey) {
        Bundle metaData = null;
        String apiKey = null;
        if (context == null || metaKey == null) {
            return null;
        }
        try {
            ApplicationInfo ai = context.getPackageManager()
                    .getApplicationInfo(context.getPackageName(),
                            PackageManager.GET_META_DATA);
            if (null != ai) {
                metaData = ai.metaData;
            }
            if (null != metaData) {
                apiKey = metaData.getString(metaKey);
            }
        } catch (PackageManager.NameNotFoundException e) {

        }
        return apiKey;
    }


    public static int getWorkyears(int workStartYear) {
        return 2015 - workStartYear;
    }

    public static String getDeviceIP(Context context) {
        String deviceIP = "";
        WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        if (wifi == null || wifi.isWifiEnabled() == false) {
            return deviceIP;
        }
        WifiInfo info = null;
        info = wifi.getConnectionInfo();
        if (null == info) {
            return deviceIP;
        }
        int ip = info.getIpAddress();
        deviceIP = String.format("%d.%d.%d.%d", (ip & 0xff), (ip >> 8 & 0xff), (ip >> 16 & 0xff), (ip >> 24 & 0xff));
        return deviceIP;
    }


    /**
     * 判断字符串是否是整数
     */
    public static boolean validateNumber(String code) {
        try {
            Integer.parseInt(code);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    public static String  getNumberFromString(String str) {
        String result = "";
        if (str == null) {
            return null;
        } else {
            for (int i = 0; i < str.length(); i++) {
                if (str.charAt(i) >= 48 && str.charAt(i) <= 57) {
                    result += str.charAt(i);
                }
            }
            return result;
        }
    }


    public static  double convertMeterToKM(double meter){
        DecimalFormat    df   = new DecimalFormat("######0.0");
        double km= meter/1000;
        return Double.parseDouble(df.format(km));
    }
}